package as3.component.manager
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	
	public class PopupManager
	{
		
		private static var instance:PopupManager;
		
		public var stage:Stage;
		
		public var box:Sprite;
		private var curBox:Sprite;
		
		private var clickList:Array;
		
		//private var _mainUI:MainUI;
		
		public function PopupManager()
		{
			if (instance) return;
			box = new Sprite();
			curBox = new Sprite();
			curBox.mouseChildren = curBox.mouseEnabled = false;
			clickList = [];
		}
		
		public static function getInstance():PopupManager
		{
			if (!instance) instance = new PopupManager();
			
			return instance;
		}
		
		public function runAt(s:Stage):void
		{
			stage = s;
			stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			stage.addChild(curBox);
		}
		
		public function addPopUp(comp:DisplayObject, basePoint:Point):void
		{
			var index:int = stage.numChildren;
			var topObj:DisplayObject = null;
//			if(index > 0)
//			{
//				topObj = stage.getChildAt(index-1);
//				if(!SwfFlash.isFlashTopMost(topObj.name) && !(topObj is SettleResultPanel))
//					topObj = null;
//			}
			comp.x = basePoint.x;
			comp.y = basePoint.y;
			box.addChild(comp);
			
			stage.addChild(box);
			
			/**
			 * marz
			 * 置顶，让优先级高的置顶
			 * addChild()可以添加已经添加过的对象，并且将此对象置顶，numChildren不增长
			 */			
			if(topObj != null)
				stage.addChild(topObj);
			stage.addChild(curBox);
		}
		
		public function removePopUp(comp:DisplayObject):void
		{
			if (comp && box.contains(comp)) {
				box.removeChild(comp);
			}
		}
		
		public function getCurBox():Sprite
		{
			return curBox;
		}
		
		private function onMouseDown(evt:MouseEvent):void
		{
			for (var i:int = 0; i < clickList.length; i++) {
				clickList[i](evt);
			}
		}
		
		public function registClick(func:Function):void
		{
			if (func == null) return;
			if (clickList.indexOf(func) == -1) {
				clickList.push(func);
			}
		}
		
		public function unRegist(func:Function):void
		{
			if (func == null) return;
			var index:int = clickList.indexOf(func);
			if (index > -1) {
				clickList.splice(index, 1);
			}
		}
		
		/**
		 * 放置最顶层
		 */		
		public function placedTop(target:DisplayObject):void
		{
			if(target != null)
			{
				if(box.contains(target) == true)
				{
					box.setChildIndex(target,box.numChildren - 1);
				}
			}
		}
	}
}